package net.example.lesson1;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.LinkedList;
import java.util.List;

/**
 * 对象引用
 * @author zhuhai
 */
public class SoftReferenceDemo {

    /**
     * 软应用，只有
     */
    public static void useSoftRef() {
        final ReferenceQueue<String> queue = new ReferenceQueue<>();
        final List<SoftReference> refList = new LinkedList<>();
        Thread thread = new Thread(() -> {
            for (; ; ) {
                try {
                    Reference<? extends String> ref = queue.remove();
                    refList.remove(ref);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        for (int i = 0; i < 20000; i++) {
            String s = new String("String-" + i);
            SoftReference<String> ref = new SoftReference<>(s, queue);
            refList.add(ref);
        }
    }

    public static void useStrongRef() {
        final List<String> list = new LinkedList<>();
        for (int i = 0; i < 20000; i++) {
            String s = new String("String-" + i);
            list.add(s);
        }
    }

    public static void main(String[] args) {
//        useStrongRef();
        useSoftRef();
        System.out.println("over");
    }
}
